package com.garbuz.svnadmin.services;

import com.garbuz.svnadmin.annotations.Service;
import com.garbuz.svnadmin.annotations.ServiceMethod;
import com.garbuz.svnadmin.data.UserResponse;
import com.garbuz.svnadmin.model.SvnModel;
import common.utils.ArrayUtil;

import java.util.List;

@Service
public class UserService extends ServiceBase
{
	@ServiceMethod
	public UserResponse createGroup(String groupName) throws Exception
	{
		synchronized (getApp())
		{
			SvnModel model = getApp().readModel();
			model.addGroup(groupName);
			getApp().writeModel(model);
		}

		return getUserList();
	}

	@ServiceMethod
	public UserResponse submitGroupUsers(String groupName, Object[] userNames) throws Exception
	{
		List<String> userNameList = ArrayUtil.asList(userNames);

		synchronized (getApp())
		{
			SvnModel model = getApp().readModel();
			model.setGroupUsers(groupName, userNameList);
			getApp().writeModel(model);
		}

		return getUserList();
	}

	@ServiceMethod
	public UserResponse submitUserGroups(String userName, Object[] groupNames) throws Exception
	{
		List<String> groupNameList = ArrayUtil.asList(groupNames);

		synchronized (getApp())
		{
			SvnModel model = getApp().readModel();
			model.setUserGroups(userName, groupNameList);
			getApp().writeModel(model);
		}

		return getUserList();
	}


	@ServiceMethod
	public UserResponse removeGroup(String userName) throws Exception
	{
		synchronized (getApp())
		{
			SvnModel model = getApp().readModel();
			model.removeGroup(userName);
			getApp().writeModel(model);
		}

		return getUserList();
	}

	@ServiceMethod
	public UserResponse createUser(String userName) throws Exception
	{
		synchronized (getApp())
		{
			SvnModel model = getApp().readModel();
			model.addUser(userName);
			getApp().writeModel(model);
		}

		return getUserList();
	}

	@ServiceMethod
	public UserResponse setPassword(String userName, String hash) throws Exception
	{
		synchronized (getApp())
		{
			SvnModel model = getApp().readModel();
			model.getUser(userName).hash = hash;
			getApp().writeModel(model);
		}

		return getUserList();
	}

	@ServiceMethod
	public UserResponse removeUser(String userName) throws Exception
	{
		synchronized (getApp())
		{
			SvnModel model = getApp().readModel();
			model.removeUser(userName);
			getApp().writeModel(model);
		}
		return getUserList();
	}

	@ServiceMethod
	public UserResponse getUsers() throws Exception
	{
		return getUserList();
	}

	private UserResponse getUserList() throws Exception
	{
		SvnModel model;
		synchronized (getApp())
		{
			model = getApp().readModel();
		}

		UserResponse result = new UserResponse();
		result.users = model.getUsers();
		result.groups = model.getGroups();

		return result;
	}
}
